<template>
    <div class="pie_chart">
        <div id="echarts" ref="echartRef" class="min"></div>
    </div>
</template>

<script lang="ts" setup>
import { ref, inject, watch } from 'vue';
const props = defineProps(['pieData', 'pieTitle']);
const echartRef = ref<any>(null);
const echarts = inject('ec');

const getEcharts = (data: any) => {
    const myChart_one = echarts.init(echartRef.value);
    myChart_one.setOption({
        title: {
            text: props.pieTitle,
            x: 'center',
            bottom: 50,
            textStyle: {
                color: '#33302D',
                fontSize: 14,
                fontWeight: 500
            }
        },
        tooltip: {
            trigger: 'item',
            formatter: function ({ data }) {
                return `${data.name}：¥${data.value}`;
            }
        },
        series: [
            {
                // name: ,
                type: 'pie',
                data: data,
                label: {
                    normal: {
                        show: true,
                        formatter: '{b} {d}%' //自定义显示格式(b:name, c:value, d:百分比)
                    }
                },
                itemStyle: {
                    normal: {
                        label: {
                            show: true,
                            formatter: function (val: any) {
                                const echartsData = data;
                                let total = 0;
                                let tarValue = 0;
                                for (let i = 0, l = echartsData.length; i < l; i++) {
                                    total += Number(echartsData[i].value);
                                    if (echartsData[i].name == val.name) {
                                        tarValue = echartsData[i].value;
                                    }
                                }
                            }
                        },
                        labelLine: { show: true }
                    }
                },
                color: ['#EE64B0', '#876BE6', '#ffb988', '#fde860', '#49B9F8', '#AFE070'],
                radius: '50%'
            }
        ]
    });
    window.addEventListener('resize', function () {
        //执行
        if (myChart_one) {
            // 判断一下，防止在初始化的时候报错，cannot read property 'resize' of null
            myChart_one.resize();
        }
    });
};
watch(
    () => props.pieData,
    val => {
        getEcharts(val);
    }
);
</script>

<style lang="scss" scoped>
.pie_chart {
    .min {
        width: 39vw;
        height: 400px;
        margin: 0 auto;
    }
}
</style>
